package com.yao.springcloud;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.EurekaServerContext;

@EnableEurekaServer
@SpringBootApplication
@RestController
public class EurekaServerApplication {

	private static final Logger logger = LoggerFactory.getLogger("EurekaServerApplication");

	@Value("${spring.application.name}")
	private String servername;

	@Value("${server.port}")
	private String port;

	@Autowired
	private EurekaServerContext eurekaServerContext;

	public static void main(String[] args) {
		SpringApplication.run(EurekaServerApplication.class, args);
	}

	@Bean
	public CommandLineRunner runner() {
		logger.info("===========服务[{} {}]启动完成===========", servername, port);
		return null;
	}

	/**
	 * @Description: 输出EurekaServer配置信息
	 * @since 2017年12月26日 上午9:57:03
	 * @author yaoym
	 * @return
	 */
	public String printEurekaServerConfigInfo() {
		StringBuffer sb = new StringBuffer();

		return sb.toString();
	}

	/**
	 * @Description: 输出EurekaServer注册列表信息
	 * @since 2017年12月26日 上午9:55:52
	 * @author yaoym
	 * @return
	 */
	public String printEurekaRegisterInfo() {
		StringBuffer sb = new StringBuffer();

		Applications applications = eurekaServerContext.getRegistry().getApplications();

		for (Application a : applications.getRegisteredApplications()) {

			a.getInstances().forEach(si -> {
				sb.append("Id : " + si.getId() + "<br>");
				sb.append("Application name : " + si.getAppName() + "<br>");
				sb.append("Host name : " + si.getHostName() + "<br>");
				sb.append("Port : " + si.getPort() + "<br>");
				sb.append("Health check url : " + si.getHealthCheckUrl() + "<br>");
				sb.append("Meta data : " + si.getMetadata() + "<br>");
				sb.append("<br>");
			});
		}

		sb.append("<br>");
		sb.append("<br>");
		sb.append("列表总数：" + applications.size());

		System.out.println(sb.toString());
		logger.info("==========="+sb.toString());
		return sb.toString();
	}

	@RequestMapping(value = "/showRegister", method = RequestMethod.GET)
	public String getRegistered() {

		return printEurekaRegisterInfo();

	}

}
